package com.app.web.base.service;

import java.io.Serializable;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.app.web.base.model.RoleResource;
import com.app.web.base.model.User;
import com.app.web.base.model.UserResource;

/**
 * Project: web<br>
 * Description: 登录Service<br>
 * Copyright (c) 2012<br>
 * All Rights Reserved.<br>
 * @author <a href="mailto:gly420@163.com">GuanLuYong</a><br>
 */
@Service("loginService") @Scope("request")
public class LoginService implements Serializable {
	private static final long serialVersionUID = 1L;
	@PersistenceContext private EntityManager em;

	/**
	 * 通过帐户取用户对象
	 * @param account
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public User findUserByAccount(String account) {
		String sql = "SELECT u FROM User u WHERE u.account = :account";
		List<User> list = em.createQuery(sql).setParameter("account", account).getResultList();
		return list.size() == 0 ? null : (User) list.get(0);
	}
	
	/**
	 * 查找用户对应的资源信息
	 * @param userId
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<UserResource> getUserResources(Long userId) {
		String sql = "SELECT ur FROM UserResource ur " +
				"WHERE ur.user.id = :userId AND ur.status=1 AND ur.res.status=1";
		return em.createQuery(sql).setParameter("userId", userId).getResultList();
	}
	/**
	 * 查找用户相关的角色，并查找角色对应的资源菜单
	 * @param userId
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<RoleResource> getRoleResources(Long userId) {
		String sql = "SELECT rr FROM RoleResource rr,User u,UserRole ur " +
				"WHERE rr.status=1 AND rr.res.status=1 AND rr.role.status=1 " +
				"AND u.id=:userId AND u=ur.user AND ur.status=1 AND ur.role=rr.role";
		return em.createQuery(sql).setParameter("userId", userId).getResultList();
	}

	public EntityManager getEm() {
		return em;
	}

	public void setEm(EntityManager em) {
		this.em = em;
	}
}